/**
 * Created by GUO on 2017/5/20.
 * 兼容iOS的ViewPager
 * @flow
 */

import React from 'react';
import {
    ViewPagerAndroid,
    Platform,
    View,
    ScrollView,
    StyleSheet,
} from 'react-native';

type Event = {
    nativeEvent:{
        position: number,
        offset: number,
    }
};

const REF_SCROLL_VIEW = 'REF_SCROLL_VIEW';

class ViewPager extends React.PureComponent{

    props: {
        initialPage?: number,
        keyboardDismissMode?: 'none'|'on-drag',
        onPageSelected?: (event: Event) => void,
        children?: Array<React.Component<*>>,
        style: ScrollView.propTypes.style,
    };

    static defaultProps = {
        initialPage: 0,
        keyboardDismissMode: 'none'
    };

    state = {width:0};
    _currentPage = 0;

    constructor(props){
        super(props);
        this._currentPage = props.initialPage || 0;
    }

    _onLayout(event){
        if(this.state.width == 0){
            this.setState({width:event.nativeEvent.layout.width});
        }
    }

    setPage(selectedPage: number): void{
        if(Array.isArray(this.props.children) &&
            selectedPage <= this.props.children.length -1){
            this.refs[REF_SCROLL_VIEW].scrollTo({x: selectedPage*this.state.width});
        }
    }

    render(){
        return (
            <ScrollView
                ref = {REF_SCROLL_VIEW}
                style={this.props.style}
                onLayout={this._onLayout.bind(this)}
                pagingEnabled={true}
                scrollEventThrottle={0}
                showsHorizontalScrollIndicator={false}
                onMomentumScrollEnd = {this._onScrollAnimationEnd.bind(this)}
                keyboardDismissMode={this.props.keyboardDismissMode}
                horizontal={true}>
                {this.state.width > 0 &&
                   React.Children.map(this.props.children,(child) => (<View style={{width:this.state.width}}>
                       {React.cloneElement(child)}
                   </View>))
                }
            </ScrollView>
        );
    }

    _onScrollAnimationEnd({nativeEvent}){
        if(this.props.onPageSelected){
            let position = nativeEvent.contentOffset.x / nativeEvent.layoutMeasurement.width;
            if(position != this._currentPage){
                this._currentPage = position;
                this.props.onPageSelected({
                    nativeEvent:{
                        position:nativeEvent.contentOffset.x / nativeEvent.layoutMeasurement.width,
                        offset:nativeEvent.contentOffset.x
                    }
                });

                console.log('====filre==',position);
            }
        }
    }

}

export default Platform.select({
    ios:ViewPager,
    android:ViewPagerAndroid
});

